package com.bjsxt.relam;

import com.bjsxt.pojo.User;
import com.bjsxt.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyRealm extends AuthorizingRealm {
    //声明业务层属性
    @Autowired
    private UserService userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("认证开始");
        //获取用户的登录名
        String uname=token.getPrincipal().toString();

        //根据用户名从数据库获取用户信息
        User user = userService.selUserInfoService(uname);

        if(user!=null){
            //校验密码
            AuthenticationInfo info=new SimpleAuthenticationInfo(token.getPrincipal(),user.getPwd(), ByteSource.Util.bytes("bjsxt"),token.getPrincipal().toString());
            return info;
        }

        return null;
    }
    /**
     * 自定义授权方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("开始授权");
        //获取当前认证的用户的身份信息
        String uname= (String) principalCollection.getPrimaryPrincipal();

        //查询当前用户具备的权限信息--从数据库
        List<String> list=userService.selPowerInfoService(uname);
        System.out.println(list);
        //查询当前用户的角色信息
        List<String> list2=userService.selRoleInfoService(uname);

        //将当前用户具备的权限信息给shiro
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(list);
        info.addRoles(list2);
        //返回
        return info;
    }


}
